<template>
    <div class="login-body">
      <div class="login-panel">
        <el-form class="login-register"
          :model="formData"
          :rules="rules"
          ref="formDataRef"
          @submit.prevent
        >
          <div class="login-title">骁合云盘</div>
          <!--邮箱输入-->
          <el-form-item prop="email">
            <el-input
                size="large"
                clearable
                placeholder="请输入邮箱"
                v-model.trim="formData.email"
                maxlength="150"
            >
              <template #prefix>
                <span class="iconfont icon-account"></span>
              </template>
            </el-input>
          </el-form-item>
          <!--登录密码-->
          <el-form-item prop="password">
            <el-input
                type="password"
                size="large"
                placeholder="请输入密码"
                v-model="formData.password"
                show-password
            >
              <template #prefix>
                <span class="iconfont icon-checkcode"></span>
              </template>
            </el-input>
          </el-form-item>

          <!--登录-记住我-->
          <el-form-item>
              <div class="rememberMe-panel">
                <el-checkbox v-model="formData.rememberMe">记住我</el-checkbox>
              </div>
            <div class="no-account">
              <a href="javascript:void(0)" class="a-link" @click="navigateTo('/forgetPassword')"
              >忘记密码？</a>
              <a href="javascript:void(0)" class="a-link" @click="navigateTo('/register')"
              >没有账号？</a>
            </div>
          </el-form-item>
          <!--找回密码--->

          <!--登录按钮-->
          <el-form-item>
            <el-button type="primary" class="op-btn" size="large" @click="Login()">
              <span>登录</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
</template>

<script setup>
import {ref, reactive, getCurrentInstance, nextTick, onMounted} from "vue";
import router from "@/router/index.js";
import {getEmail, login} from "@/api/login.js";
const { proxy } = getCurrentInstance();

const navigateTo = path => router.push(path);
const formData = ref({});
const formDataRef = ref();
const rules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入邮箱地址'));
        }
        const qqRegex = /^[\w-]+(\.[\w-]+)*@qq\.com$/;
        const neteaseRegex = /^[\w-]+(\.[\w-]+)*@(163|126|yeah)\.com$/;

        if (qqRegex.test(value) || neteaseRegex.test(value)) {
          callback(); // 验证通过
        } else {
          callback(new Error('请输入有效的QQ邮箱或网易邮箱'));
        }
      },
      trigger: 'blur'
    }
  ],
};

// 在组件挂载时自动填充表单
onMounted(() => {
  const savedEmail = sessionStorage.getItem('email');
  const savedPassword = sessionStorage.getItem('password');
  const savedRememberMe = sessionStorage.getItem('rememberMe') === 'true';

  console.log("挂载界面", savedEmail);
  if (savedRememberMe && savedEmail && savedPassword) {
    formData.value.email = savedEmail;
    formData.value.password = savedPassword;
    formData.value.rememberMe = savedRememberMe;
  }
});

//前往注册界面
const toRegister=()=>{
  router.push('/register').then(() => {
    // 强制刷新页面
    window.location.reload();
  });
}
//前往重置密码界面
const toForgetPassword=()=>{
  router.push('/forgetPassword').then(() => {
    // 强制刷新页面
    window.location.reload();
  });
}
//登录
const Login = ()=>{
  formDataRef.value.validate((valid) => {
    if(!valid){
      proxy.$message({
        message:"请输入正确的邮箱",
        type:'warning'
      })
      return;
    }
    const data={
      username:formData.value.email,
      password:formData.value.password
    }
    login(data).then(res=>{
      console.log("登录：",res.data);
      if(res.data.code===200){
        proxy.$message({
          message:'登录成功',
          type:'success'
        })
        console.log("记住我",formData.value.rememberMe);

        //全局存储用户信息--会话存储
        sessionStorage.setItem('userInfo',JSON.stringify(res.data.userInfo));
        if (formData.value.rememberMe) {
          console.log("存储数据");
          sessionStorage.setItem('email', formData.value.email);
          sessionStorage.setItem('password', formData.value.password);
          sessionStorage.setItem('rememberMe', 'true'); // 存储为字符串
        } else {
          sessionStorage.removeItem('email');
          sessionStorage.removeItem('password');
          sessionStorage.removeItem('rememberMe');
        }


        navigateTo('/framework/allFile');
      }
    })

  })
}
</script>

<style lang="scss" scoped>
.login-body{
  height:calc(100vh);
  background-size: cover; /**完全覆盖body区域**/
  background: url('@/assets/login_bg.jpg'); /**@默认指向src目录**/
  display: flex;
  justify-content: right;
  /**.bg{
    flex:1;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
  }**/
  .login-panel{
    width:430px;
    margin-right: 10%;
    margin-top:calc((100vh - 600px)/2);
    .login-register{
      padding:25px;
      background: #ffffff;
      border: 2px solid #3498db;
      border-radius: 5px;
      .login-title{
        text-align:center;
        font-size: 18px;
        font-weight: bold;
        margin-bottom:20px;
      }
      .send-email-panel{
        display: flex;
        width:100%;
        justify-content: space-between;
        .send-email-btn{
          margin-left:5px;
        }
      }
      .rememberMe-panel{
        width:100%;
      }
      .no-account{
        width:100%;
        display: flex;
        justify-content: space-between;
      }
      .op-btn{
        width:100%;
      }
    }
  }
  .check-code-panel{
    width:100%;
    display: flex;
    .check-code{
      margin-left:5px;
      cursor:pointer;
    }
  }
  .login-btn-qq{
    margin-top:20px;
    text-align:center;
    display: flex;
    align-items: center;
    justify-content: center;
    img{
      cursor:pointer;
      margin-left:10px;
      width:20px;
    }
  }
}
</style>